from observe import *
import JSObject
import database as db
js = JSObject.JS_SocketController()


def fractSec(s):
    "Return days, hours, minutes, seconds given a value in seconds"
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    return d, h, m, s

def minutes(val):
    hr = ""
    mn = "0:"
    sec = "00" 
    try:
        val = int(val)
        d, h, m, s = fractSec(val)
        if (h > 0):
                hr = str(h)+":"
        else:
                hr = ""
        mn = str(m)+":"
        if (s < 10):
                sec = "0"+str(s)
        else:
                sec = str(s)
    except: pass
    return hr+mn+sec


def initClient(client):
    volChange(obs_volume.value)
    plChange(obs_playlist.version)
    cur_songChange(obs_curSong.value)
    stateChange(obs_state.value)
    elapsedChange(obs_elapsedTime.value)
    totalChange(obs_totalTime.value)
    randomChange(obs_random.value)
    repeatChange(obs_repeat.value)
js.onConnect=initClient


def cur_songChange(item):
    try: p = int(item['pos'])
    except: p = -1
    js.push(u"['setCurSong',%d]" % p)
obs_curSong.connect(cur_songChange)

def randomChange(value):
    js.push("['setRandom', '%d']" % value)
obs_random.connect(randomChange)

def repeatChange(value):
    js.push("['setRepeat', '%d']" % value)
obs_repeat.connect(repeatChange)

def stateChange(value):
    js.push("['setState', '%s']" % value)
obs_state.connect(stateChange)


def elapsedChange(value):
    js.push("['setTime', %s, false]" % value)
obs_elapsedTime.connect(elapsedChange)


def totalChange(value):
    js.push("['setTime', 0, '%s']" % value)
obs_totalTime.connect(totalChange)


def plChange(ver):
    plids = '['+','.join(obs_playlist.items)+']'
    time = ""
    d,h,m,s = fractSec(obs_playlist.time)
    if d > 0:
        time += str(d)+" day"
        if d > 1: time += "s, "
        else: time += ", "
    if h > 0: 
        time += str(h)+" hour"
        if h > 1: time += "s, "
        else: time += ", "
    time += str(m)+" minute"
    if m == 1: time += ", "
    else: time += "s, "
    time += str(s)+" second"
    if s == 1: time += "."
    else: time += "s."
    js.push("['setPlaylist', %s, %d, '%s']" % (plids, ver, time))
obs_playlist.connect(plChange)


def volChange(value):
    js.push("['setVol', %s]" % value)
obs_volume.connect(volChange)

def dbChange(value):
    js.push("['setDB', '%s']" % value['db_update'])
obs_dbStats.connect(dbChange)


